//
//  KWMStringUtil.m
//  IWant_User
//
//  Created by kevin on 12/10/14.
//  Copyright (c) 2014 kollway. All rights reserved.
//

#import "KWMStringUtil.h"
#import <CommonCrypto/CommonDigest.h>
#import "GTMBase64.h"

static NSDateFormatter *yearMonthDayFormatter;
static NSDateFormatter *monthDayFormatter;
static NSDateFormatter *timeFormatter;

@implementation KWMStringUtil {
    
}

+ (void)initialize {
    [super initialize];
    yearMonthDayFormatter = [[NSDateFormatter alloc] init];
    [yearMonthDayFormatter setDateFormat:@"yyyy-MM-dd"];
    
    monthDayFormatter = [[NSDateFormatter alloc] init];
    [monthDayFormatter setDateFormat:@"MM-dd"];
    
    timeFormatter = [[NSDateFormatter alloc] init];
    [timeFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
}


+ (NSString *)MD5:(NSString *)input {
    const char *cStr = [input UTF8String];
    unsigned char digest[16];
    CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}

+ (BOOL)isEmpty:(NSString *)input {
    return [input isKindOfClass:[NSNull class]] || input == nil || [input length] <= 0;
}

+ (BOOL)isBlank:(NSString *)input {
    return [self isEmpty:input] ||
    ([[input stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0);
}

+ (BOOL)isNumberString:(NSString *)input {
    if([input isKindOfClass:[NSNull class]]){
        return NO;
    }
    if([KWMStringUtil isBlank:input]){
        return NO;
    }
    
    int len = input.length;
    for(int i = 0; i < len; i++){
        unichar c = [input characterAtIndex:i];
        if(!isnumber(c)){
            return NO;
        }
    }
    return YES;
}

+ (BOOL)isPhone:(NSString *)input {
    if([input isKindOfClass:[NSNull class]]){
        return NO;
    }
    if(! [KWMStringUtil isNumberString:input]){
        return NO;
    }
    
    int len = [input length];
    if(len != 11){
        return NO;
    }
    
    for(int i = 0; i < len; i++){
        unichar c = [input characterAtIndex:i];
        if(! isdigit(c)){
            return NO;
        }
    }
    
    return YES;
}

+ (NSString *)readableDateString:(NSDate *)date {
    NSCalendarUnit dateFlags = NSYearCalendarUnit|
    NSMonthCalendarUnit|
    NSDayCalendarUnit|
    NSHourCalendarUnit|
    NSMinuteCalendarUnit|
    NSSecondCalendarUnit;
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *dateComponents = [gregorianCalendar components:dateFlags fromDate:date];
    NSDateComponents *nowComponents = [gregorianCalendar components:dateFlags fromDate:[NSDate new]];
    
    if((dateComponents.year < nowComponents.year)||
       (dateComponents.month < nowComponents.month)||
       (dateComponents.day < nowComponents.day)){
        return [KWMStringUtil yearMonthDateString:date];
    }
    
    int hourSub = nowComponents.hour - dateComponents.hour;
    if(hourSub > 0){
        return [[NSString alloc] initWithFormat:@"%@小时前", @(hourSub)];
    }
    
    int minuteSub = nowComponents.minute - dateComponents.minute;
    if(minuteSub > 0){
        return [[NSString alloc] initWithFormat:@"%@分钟前", @(minuteSub)];
    }
    
    int secondSub = nowComponents.second - dateComponents.second;
    if(secondSub > 5){
        return [[NSString alloc] initWithFormat:@"%@秒前", @(secondSub)];
    }else{
        return [[NSString alloc] initWithFormat:@"刚刚"];
    }
}

+ (NSString *)yearMonthDateString:(NSDate *)date {
    return [yearMonthDayFormatter stringFromDate:date];
}

+ (NSString *)dateToString:(NSDate *)date format:(NSString *)formatStr {
    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:formatStr];
    return [f stringFromDate:date];
}

+ (NSDate *)stringToDate:(NSString *)dateStr format:(NSString *)formatStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [formatter setTimeZone:timeZone];
    [formatter setDateFormat:formatStr];
    return [formatter dateFromString:dateStr];
}


+ (NSString *)monthDateString:(NSDate *)date {
    return [monthDayFormatter stringFromDate:date];
}


+ (NSString *)getFileName:(NSString *)filePath {
    if([self isEmpty:filePath]){
        return @"";
    }
    
    return [filePath lastPathComponent];
}

+ (NSString *) trimPhoneNumber:(NSString *)string {
    NSCharacterSet * invalidNumberSet = [NSCharacterSet characterSetWithCharactersInString:@" -\n_!@#$%^&*()[]{}'\".,<>:;|\\/?+=\t~` "];
    
    NSString  * result  = @"";
    NSScanner * scanner = [NSScanner scannerWithString:string];
    NSString  * scannerResult;
    
    [scanner setCharactersToBeSkipped:nil];
    
    while (![scanner isAtEnd])
    {
        if([scanner scanUpToCharactersFromSet:invalidNumberSet intoString:&scannerResult])
        {
            result = [result stringByAppendingString:scannerResult];
        }
        else
        {
            if(![scanner isAtEnd])
            {
                [scanner setScanLocation:[scanner scanLocation]+1];
            }
        }
    }
    
    return result;
}

+ (NSString *)flattenHTML:(NSString *)html {
    if([self isEmpty:html]){
        return html;
    }
    
    NSScanner *theScanner;
    NSString *text = nil;
    
    theScanner = [NSScanner scannerWithString:html];
    
    while (! [theScanner isAtEnd]) {
        
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
                [ NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }
    
    return [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

+ (NSString *)getPureText:(NSString *)input {
    if([self isEmpty:input]){
        return input;
    }
    input = [input stringByReplacingOccurrencesOfString:@" " withString:@""];
    input = [input stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    input = [input stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    input = [input stringByReplacingOccurrencesOfString:@"\b" withString:@""];
    input = [input stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    input = [input stringByReplacingOccurrencesOfString:@"\f" withString:@""];
    return input;
}


+ (NSString *)getShortText:(NSString *)text maxLen:(int)maxLen{
    if([KWMStringUtil isEmpty:text]){
        return text;
    }
    if(text.length > maxLen){
        NSString *moreStr = @"…";
        text = [text substringWithRange:NSMakeRange(0, (NSUInteger) (maxLen - moreStr.length))];
        text = [text stringByAppendingString:moreStr];
    }
    
    return text;
}

+ (NSString *)urlencode:(NSString *)input {
    NSMutableString *output = [NSMutableString string];
    const unsigned char *source = (const unsigned char *)[input UTF8String];
    int sourceLen = strlen((const char *)source);
    for (int i = 0; i < sourceLen; ++i) {
        const unsigned char thisChar = source[i];
        if (thisChar == ' '){
            [output appendString:@"+"];
        } else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
                   (thisChar >= 'a' && thisChar <= 'z') ||
                   (thisChar >= 'A' && thisChar <= 'Z') ||
                   (thisChar >= '0' && thisChar <= '9')) {
            [output appendFormat:@"%c", thisChar];
        } else {
            [output appendFormat:@"%%%02X", thisChar];
        }
    }
    return output;
}

+ (NSString *)fitImageWidthHtmlContent:(NSString *)htmlContent maxWidth:(NSInteger)width{
    
    NSString *preHtml = [[NSString alloc] initWithFormat:@"<!DOCTYPE HTML><html><head><script type=\"text/javascript\">function ResizeImages(myimg){var maxWidth = %d; var oldWidth; var oldwidth,oldHeight;var i;myimg.style.cssText=\"\"; if(myimg.width > maxWidth){oldWidth = myimg.width; oldHeight = myimg.height; myimg.width = maxWidth; myimg.height = oldHeight*(maxWidth/oldWidth);}}</script><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"><style>* {font-family: Arial,Helvetica,\"Nimbus Sans L\",sans-serif;-webkit-text-size-adjust: none;}div.container img{padding-bottom:10px;}</style></head><body style=\"-moz-user-select: none;-webkit-user-select: none;width:%dpx;px;margin-left:10px;padding: 0px;margin-right:10px\">",
                         width, width];
    NSString *afterHtml = @"</body></html>";
    htmlContent = [htmlContent stringByReplacingOccurrencesOfString:@"<img" withString:@"<img onload=\"ResizeImages(this);\""];
    htmlContent = [NSString stringWithFormat:@"%@%@%@", preHtml, htmlContent, afterHtml];
    return htmlContent;
}

+ (BOOL)isMobileNumber:(NSString *)mobileNum
{
    static NSString *TRUE_PHONE = @"^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", TRUE_PHONE];
    
    return [regextestmobile evaluateWithObject:mobileNum];
}

+ (NSString*)encodeBase64String:(NSString * )input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    data = [GTMBase64 encodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}

+ (NSString*)decodeBase64String:(NSString * )input {
    NSData *data = [input dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    data = [GTMBase64 decodeData:data];
    NSString *base64String = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return base64String;
}


+ (NSString *)timeDateString:(NSDate *)date {
    return [timeFormatter stringFromDate:date];
}


+(NSString *) dateformatToYear:(long long) time{

    
    //去除毫秒
    NSString *timeStr = [NSString stringWithFormat:@"%lld",time];
    if ([timeStr length] == 13) {
        time = time/1000;
    }
    //设置时间
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    NSDate *addTimesp = [NSDate dateWithTimeIntervalSince1970:time];
    NSString *addTimespStr = [formatter stringFromDate:addTimesp];
    return addTimespStr;
}

@end